<template>
  <basic-container>
    <div class="flex flex-row sb">
      <b>兑换配置</b>
      <div>
        <el-button
            type="primary"
            v-if="!actionFlag"
            @click="confirm"
        >
          保存
        </el-button>
        <el-button
            type="primary"
            v-if="actionFlag && !isEnable"
            @click="changeStatus"
        >
          启用
        </el-button>
        <el-button
            type="primary"
            v-if="actionFlag && isEnable"
            @click="changeStatus"
        >
          禁用
        </el-button>
        <el-button
            type="primary"
            v-if="actionFlag && !isEnable"
            @click="changeAction('edit')"
        >
          编辑
        </el-button>
      </div>
    </div>
    <avue-form
        ref="form"
        v-model="form"
        :option="formOption"
        :upload-exceed="uploadExceed"
        :upload-error="uploadError"
        :upload-change="$uploadChange"
        :upload-before="uploadBefore"
    >
      <template #rule="{disabled,placeholder}">
        <span v-if="disabled">
          {{form.rule}}
        </span>
        <el-input
            v-else
            type="textarea"
            :placeholder="placeholder"
            v-model="form.rule"
            :autosize="true"
            maxlength="2000"
            show-word-limit
        >
        </el-input>
      </template>


    </avue-form>
    <div class="spacing-b"></div>
  </basic-container>
</template>

<script>
import {mapGetters} from 'vuex';
import {getObj, putObj, putObjStatus} from '@/api/core/cannedConfiguration';
import {formOption} from '@/const/crud/points/redemption-configuration';
import {REDEMPTION_STATUS, REDEMPTION_TYPE} from '@/const/type';

export default {
  name: 'redemptionConfig',

  data() {
    return {
      form: {
      },
      loading: false,
      REDEMPTION_TYPE,
      action: 'view',
    };
  },
  computed: {
    ...mapGetters(['userInfo', 'access_token']),
    actionFlag() {
      return this.action === 'view';
    },
    formOption() {
      return formOption(this.actionFlag,this.form.type);
    },
    isEnable() {
      return this.form.status === REDEMPTION_STATUS.ON;
    },
  },
  mounted() {
    this.getDetail();
  },
  watch: {
    'form.type': {
      immediate:true,
      handler(value) {
        if (!this.actionFlag) {
          this.form.ids = [];
        }
        this.$nextTick(()=>{
          this.$refs.form.updateDic('ids')
        })
      },
    },
  },
  methods: {
    async getDetail() {
      const res = await getObj();
      if (res.data.data && res.data.data.type) {
        this.form = {...res.data.data};
        this.form.ids = JSON.parse(this.form.ids);
        this.form.files = JSON.parse(this.form.files);
        this.action = 'view';
      } else {
        this.action = 'add';
        this.form = {
            type:REDEMPTION_TYPE.EXCHANGE_COUPON
        }
      }
    },
    confirm() {
      this.$refs.form.validate(async (valid, done) => {
        if (valid) {
          this.loading = true;
          try {
            const params = {...this.form};
            console.log(params);
            params.files = JSON.stringify(params.files);
            params.ids = JSON.stringify(params.ids);
            const callback = putObj;
            await callback(params);
            this.$message.success('操作成功');
            this.action = 'view';
            await this.getDetail();
            done();
            this.loading = false;
          } catch (error) {
            done();
            this.loading = false;
            throw new Error(error);
          }
        }
      });
    },
    //文件大小
    uploadError(error, column) {
      if (error === '文件太大不符合') {
        this.$message.warning(`文件大小不能超过${column.fileSize / 1024}M`);
      }
    },
    uploadExceed(limit, files, fileList, column) {
      console.log(limit, files, fileList, column);
      this.$message.error(`只能上传${limit}个文件`);
    },
    uploadBefore(file, done, loading, column) {
      const fileExtend = file.name
          .substring(file.name.lastIndexOf('.'))
          .toLowerCase();
      console.log(fileExtend)
      if ( '.jpg,.png,.jpeg,.webp,.heic'.indexOf(fileExtend) === -1) {
        this.$message.error('请上传jpg/png/jpeg/webp/heic类型的文件')
        loading();
        return false
      }
      done();

    },
    async changeStatus() {
      await putObjStatus(this.form.id, this.form.status === REDEMPTION_STATUS.ON ? REDEMPTION_STATUS.OFF : REDEMPTION_STATUS.ON);
      this.getDetail();
    },
    changeAction(action) {
      this.action = action;
    },
  },
};
</script>

<style lang="scss" scoped>
.spacing-b{
  height: 50px;
}
</style>
